package com.labbit.platform.commons.session;

import com.labbit.platform.commons.exception.UnauthorizedException;
import com.labbit.platform.commons.exception.message.SessionError;
import com.labbit.platform.commons.properties.CommonProperties;
import com.labbit.platform.commons.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * session 工具类
 * @author ChenYu
 * @date 2017/12/14 19:57
 */
@Slf4j
public abstract class SessionUtils {

    private static ISession<SessionData> session;
    private static CommonProperties properties;
    static {
        properties = SpringContextHolder.getBean("commonProperties");
        log.info("session store : {}", properties.getSessionStore());
        session = SpringContextHolder.getBean(properties.getSessionStore());
    }

    private static String TOKEN = properties.getTokenName();

    /**
     * 登录后缓存在当前线程
     */
    private static ThreadLocal<SessionData> sessionDataThreadLocal = new ThreadLocal<>();

    /**
     * 登录验证
     * @author ChenYu
     */
    public static void verifyLogin() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader(TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new UnauthorizedException(SessionError.NOT_TOKEN);
        }
        SessionData sessionData = getSession(token);
        if (null == sessionData) {
            throw new UnauthorizedException(SessionError.NOT_LOGIN);
        }
        sessionDataThreadLocal.set(sessionData);
    }

    /**
     * 获取当前登录人的Session信息
     */
    public static SessionData getCurrentSession() {
        SessionData sessionData = sessionDataThreadLocal.get();
        if (null == sessionData) {
            throw new UnauthorizedException(SessionError.NOT_LOGIN);
        }
        return sessionData;
    }

    public static SessionData getSession(String key) {
        return session.get(key);
    }

    public static void putSession(String key, SessionData data) {
         session.put(key, data);
    }
    
    public static void removeSession(String key) {
        session.remove(key);
   }


   /**
    * 获取当前登录人ID
    */
    public static String getCurrentUserId() {
        return getCurrentSession().getId();
    }

}
